package loginuser

import (
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks2/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/app"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/gorm"
	Log "github.com/cihub/seelog"
)

type LoginUserDao struct {
	app.DaoBaseFunc
}

// 修改密码
func (dao LoginUserDao) EditPass(dbName, id, newPass, oldPass, modifieder, owner string, edition int64) *msgentity.MsgEntity {
	txt := `
UPDATE ${BaseSystem}login_user SET
	pass = @newPass,
	modified_date = NOW(),
	modifieder = @modifieder,
	edition = edition +1
WHERE id = @id
AND pass = @oldPass
AND edition = @edition`
	txt = strings.Replace(txt, "${BaseSystem}login_user", owner, -1)

	where := map[string]interface{}{
		"id":         id,
		"modifieder": modifieder,
		"newPass":    newPass,
		"oldPass":    oldPass,
		"edition":    edition,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return msgentity.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(7002, "数据没有影响值！")
	}

	return msgentity.Success(7999, "更新成功")
}

// 重置密码
func (dao LoginUserDao) ResetPass(dbName, id, newPass, modifieder, owner string, edition int64) *msgentity.MsgEntity {
	txt := `
UPDATE ${BaseSystem}login_user SET
	pass = @newPass,
	modified_date = NOW(),
	modifieder = @modifieder,
	edition = edition +1
WHERE id = @id
AND edition = @edition`
	txt = strings.Replace(txt, "${BaseSystem}login_user", owner, -1)

	where := map[string]interface{}{
		"id":         id,
		"modifieder": modifieder,
		"newPass":    newPass,
		"edition":    edition,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return msgentity.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(7002, "数据没有影响值！")
	}

	return msgentity.Success(7999, "更新成功")
}

// 根据用户编号设置用户类型
func (dao LoginUserDao) EditUserType(dbName, id, sType, owner string) *msgentity.MsgEntity {
	txt := `UPDATE ${BaseSystem}login_user SET type = @sType WHERE id = @id`
	txt = strings.Replace(txt, "${BaseSystem}login_user", owner, -1)

	where := map[string]interface{}{
		"id":   id,
		"type": sType,
	}

	dbResult := gorm.Exec(txt, where)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return msgentity.Err(7001, "更新数据发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(7002, "数据没有影响值！")
	}

	return msgentity.Success(7999, "更新成功")
}
